package com.ztc.ZtcRoute.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.aqgj.util.JsonWrapper;
import com.ztc.ZtcClassesForSale.bean.ZtcClassesForSale;
import com.ztc.ZtcClassesForSale.dao.ZtcClassesForSaleDao;
import com.ztc.ZtcClassesForSale.service.ZtcClassesForSaleManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ztc.ZtcClasses.bean.ZtcClasses;
import com.ztc.ZtcClasses.service.ZtcClassesManager;
import com.ztc.ZtcRoute.bean.ZtcRoute;
import com.ztc.ZtcRoute.service.ZtcRouteManager;
import com.ztc.ZtcRouteAttachment.bean.ZtcRouteAttachment;
import com.ztc.ZtcRouteAttachment.service.ZtcRouteAttachmentManager;
import com.ztc.ZtcRoutePrice.bean.ZtcRoutePrice;
import com.ztc.ZtcRoutePrice.service.ZtcRoutePriceManager;
import com.ztc.ZtcRouteSite.bean.ZtcRouteSite;
import com.ztc.ZtcRouteSite.service.ZtcRouteSiteManager;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.service.AttachmentManager;
import com.aqgj.User.bean.User;

@Controller
@RequestMapping("ztc_route_action")
public class ZtcRouteAction {
	@Autowired
	private ZtcRouteManager ztcRouteManager;
	@Autowired
	private ZtcClassesForSaleDao ztcClassesForSaleDao;
	@Autowired
	private ZtcClassesManager ztcClassesManager;
	@Autowired
	private ZtcRouteSiteManager ztcRouteSiteManager;
	@Autowired
	private ZtcRoutePriceManager ztcRoutePriceManager;
	@Autowired
	private ZtcClassesForSaleManager ztcClassesForSaleManager;
	@Autowired
	private ZtcRouteAttachmentManager ztcRouteAttachmentManager;
	@Autowired
	private ZtcTransportManager ztcTransportManager;
	@Autowired
	private AttachmentManager attachmentManager;
	private static final Logger log = LogManager.getLogger(ZtcRoute.class);
	private static final SimpleDateFormat DATE_FORMET = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 添加线路
	 * @param data 梯形表数据包括站点和价格
	 * @param name 线路名称
	 * @param remark 备注
	 * @param attachment 附件包括图片和说明
	 * @param request
	 * @param session
	 * @return 操作结果信息
	 */
	@RequestMapping("sign")
	@ResponseBody
	public HashMap<String, Object> save(String data, String name, String remark, String attachment,
			HttpServletRequest request, HttpSession session) {
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if(user==null||"".equals(user)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作线路");
			log.info("非运营公司或车方不可操作线路");
			return wapper;
		}
		if(transport.getStatus()==4){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可操作线路");
			log.info("该用户公司已被冻结，不可操作线路");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if("".equals(name)||",".equals(name)||name==null){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "线路名称不可为空");
			log.info("线路名称不可为空");
			return wapper;
		}
		String[] siteNames = name.split(",");
		String fromSite = siteNames[0];
		String toSite =(siteNames.length==1?"":siteNames[1]);
		if(fromSite==null||"".equals(fromSite)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "线路名称起点名称不可为空");
			log.info("线路名称起点名称不可为空");
			return wapper;
		}
		if(fromSite.length()>32){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "线路名称起点名称长度不可超过32位");
			log.info("线路名称起点名称长度不可超过32位");
			return wapper;
		}
		if(toSite==null||"".equals(toSite)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "线路名称终点名称不可为空");
			log.info("线路名称终点名称不可为空");
			return wapper;
		}
		if(toSite.length()>32){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "线路名称终点名称长度不可超过32位");
			log.info("线路名称终点名称长度不可超过32位");
			return wapper;
		}
		examineArgument(argumentsAndRoles, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		int status = 0;
		if (transport.getType() == 3) {
			status = 1;
		}
		JSONArray dataArray = JSON.parseArray(data);
		if (dataArray != null) {
			if (isEmptyPrice(dataArray)) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "线路价格不可为空");
				log.info("线路价格不可为空");
				return wapper;
			}
		}
		examineRouteInfo(wapper, dataArray);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		ZtcRoute route = new ZtcRoute();
		Date date = new Date();
		route.setName(name == null ? null : name.replace(",", "-"));
		route.setRemark(remark);
		route.setStatus(status);
		route.setAddTime(date);
		route.setApplyTime(date);
		route.setApplyUserName(user == null ? ""
				: (user.getName() == null || "".equals(user.getName())) ? user.getAccount() : user.getName());
		route.setFkApplyUserId(user == null ? "" : user.getId());
		route.setFkZtcTransportId(user == null ? "" : user.getTransportId());
		String routeId = ztcRouteManager.save(route);
		if (routeId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网路错误");
			log.info("网络错误");
			return wapper;
		}
		saveRouteInfo(wapper, dataArray, routeId);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		JSONArray attachmentGroupArray = JSON.parseArray(attachment);
		for(int i=0;i<attachmentGroupArray.size();i++){
			JSONObject attachmentObject=attachmentGroupArray.getJSONObject(i);
			String attachmentString=attachmentObject.getString("group");
			JSONArray attachmentArray = JSON.parseArray(attachmentString);
			saveRouteAttachmentInfo(request, wapper, routeId, attachmentArray,i);
		}
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "添加成功");
		log.info("添加成功");
		return wapper;
	}

	/**
	 * 判断梯形表内价格信息是否为空
	 * @param dataArray
	 * @return false：不为空，true：为空
	 */
	private boolean isEmptyPrice(JSONArray dataArray) {
		boolean isEmptyPrice = false;
		int emptyPriceCount = 0;
		int siteSize = 1;
		for (int i = 1; i < dataArray.size(); i++) {
			siteSize++;
			JSONObject siteObject = dataArray.getJSONObject(i);
			JSONArray price = siteObject.getJSONArray("cell");
			for (int j = 0; j < price.size(); j++) {
				JSONObject object = price.getJSONObject(j);
				if ("".equals(object.getString("pirce")) || "0".equals(object.getString("pirce"))) {
					emptyPriceCount++;
				}
			}
		}
		int priceGridCount = 0;
		for (int i = siteSize - 1; i >= 1; i--) {
			priceGridCount += i;
		}
		if (priceGridCount == emptyPriceCount) {
			isEmptyPrice = true;
		}
		return isEmptyPrice;
	}

	/**
	 *检验线路站点与价格信息是否合理
	 * @param wapper 用于装载检验信息
	 * @param dataArray 梯形表数据包括站点和价格
	 */
	private void examineRouteInfo(HashMap<String, Object> wapper, JSONArray dataArray) {
		if (dataArray != null) {
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject siteObject = dataArray.getJSONObject(i);
				String siteName = siteObject.getString("name");
				String siteLat = siteObject.getString("lat");
				String siteDetail = siteObject.getString("detailed");
				String[] lat_lng = siteLat.split(",");
				String lng = lat_lng[0];
				String lat = (lat_lng.length==1?"":lat_lng[1]);
				LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
				if(siteName==null||"".equals(siteName)){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "站点所在城市不可为空");
					log.info("站点所在城市不可为空");
					return;
				}
				if(siteName.length()>32){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "站点所在城市长度不可超过32位");
					log.info("站点所在城市长度不可超过32位");
					return;
				}
				if(siteDetail==null||"".equals(siteDetail)){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "站点详细地址不可为空");
					log.info("站点详细地址不可为空");
					return;
				}
				if(siteDetail.length()>32){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "站点详细地址长度不可超过32位");
					log.info("站点详细地址长度不可超过32位");
					return;
				}
				if(lng==null||"".equals(lng)){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "经度不可为空");
					log.info("经度不可为空");
					return;
				}
				if(lng.length()>32){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "经度长度不可超过32位");
					log.info("经度长度不可超过32位");
					return;
				}
				argumentsAndRoles.put(lng + "#经度格式如'106.544338'范围-180.0000~180.0000",
						"^-?((0|1?[0-7]?[0-9]?)(([.][0-9]{1,})?)|180(([.][0]{1,})?))$");
				if(lat==null||"".equals(lat.trim())){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "经度不可为空");
					log.info("经度不可为空");
					return;
				}
				if(lat.trim().length()>32){
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "纬度长度不可超过32位");
					log.info("纬度长度不可超过32位");
					return;
				}
				argumentsAndRoles.put(lat.trim() + "#纬度格式如'29.590661'范围-90.0000~90.0000",
						"^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,})?)|90(([.][0]{1,})?))$");
				examineArgument(argumentsAndRoles, wapper);
				if ("false".equals(String.valueOf(wapper.get("success")))) {
					return;
				}
				JSONArray price = siteObject.getJSONArray("cell");
				if (price != null) {
					examineRoutePriceAssistant(wapper, argumentsAndRoles, price);
					if ("false".equals(String.valueOf(wapper.get("success")))) {
						return;
					}
				}
			}
		}
	}

	/**
	 * 检验线路价格信息是否合理
	 * @param wapper 用于装载检验信息
	 * @param argumentsAndRoles 用于装载待检参数规则和说明的集合
	 * @param price 价格信息集合
	 */
	private void examineRoutePriceAssistant(HashMap<String, Object> wapper, LinkedHashMap<String, String> argumentsAndRoles,  JSONArray price) {
		for (int j = 0; j < price.size(); j++) {
			JSONObject object = price.getJSONObject(j);
			String priceString = object.getString("pirce");
			String distanceString = object.getString("distance");
			if(!"".equals(priceString)&&priceString!=null){
				argumentsAndRoles.clear();
				if (priceString.length()>10) {
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "价格的长度不可超过10");
					return;
				}
				argumentsAndRoles.put(priceString + "#价格的格式如'1.01'",
						"^(([1-9][0-9]{0,9})|([0-9])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,7}.[0-9]{1})|([1-9][0-9]{1,6}.[0-9]{2})))$");
				if(!"".equals(distanceString)&&distanceString!=null){
					if (distanceString.length()>8) {
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", "距离的长度不可超过8");
						return;
					}
					argumentsAndRoles.put(distanceString + "#距离的格式如'1.01'",
							"^(([1-9][0-9]{0,7})|([0-9])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,5}.[0-9]{1})|([1-9][0-9]{1,4}.[0-9]{2})))$");
				}
				examineArgument(argumentsAndRoles, wapper);
			}
		}
	}

	/**
	 * 存放线路的站点和价格信息
	 * @param wapper 用于装载操作信息
	 * @param dataArray 梯形表数据包括站点，价格
	 * @param routeId 线路id
	 */
	private void saveRouteInfo(HashMap<String, Object> wapper, JSONArray dataArray, String routeId) {
		if (dataArray != null) {
			List<ZtcRouteSite> routeSites = new ArrayList<ZtcRouteSite>();
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject siteObject = dataArray.getJSONObject(i);
				String siteName = siteObject.getString("name");
				String siteLat = siteObject.getString("lat");
				String siteDetail = siteObject.getString("detailed");
				ZtcRouteSite routeSite = new ZtcRouteSite();
				routeSite.setName(siteDetail);
				routeSite.setAreaCity(siteName);
				routeSite.setSequence(i + 1);
				routeSite.setType(0);
				routeSite.setFkZtcRouteId(routeId);
				routeSite.setLat(siteLat);
				String siteId = ztcRouteSiteManager.save(routeSite);
				if (siteId == null) {
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "网路错误");
					log.info("网络错误");
					return;
				}
				routeSite.setId(siteId);
				routeSites.add(routeSite);
				JSONArray price = siteObject.getJSONArray("cell");
				if (price != null) {
					generateRoutePriceAssistant(wapper, routeId, routeSites, siteId, price);
					if ("false".equals(String.valueOf(wapper.get("success")))) {
						return;
					}
				}
			}
		}
	}

	/**
	 * 生成线路价格信息
	 * @param wapper 用于装载操作信息
	 * @param routeId 线路id
	 * @param routeSites 线路价格开始站点集合
	 * @param siteId 线路价格结束站点id
	 * @param price 线路价格集合
	 */
	private void generateRoutePriceAssistant(HashMap<String, Object> wapper, String routeId,
			List<ZtcRouteSite> routeSites, String siteId, JSONArray price) {
		for (int j = 0; j < price.size(); j++) {
			JSONObject object = price.getJSONObject(j);
			if (!"".equals(object.getString("pirce")) && !"".equals(object.getString("distance"))) {
				ZtcRouteSite startRouteSite = routeSites.get(j);
				ZtcRoutePrice routePrice = new ZtcRoutePrice();
				routePrice.setPrice(object.getString("pirce"));
				routePrice.setDistance(object.getString("distance"));
				routePrice.setFkRouteStartSiteId(startRouteSite.getId());
				routePrice.setFkRouteEndSiteId(siteId);
				routePrice.setType(0);
				routePrice.setFkZtcRouteId(routeId);
				String priceId = ztcRoutePriceManager.save(routePrice);
				if (priceId == null) {
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "网路错误");
					log.info("网络错误");
					return;
				}
			}
		}
	}

	/**
	 * 按照正则表达式检验参数是否合法
	 * @param arguments 参数集合
	 * @param wapper 用于装载检验结果
	 */
	private void examineArgument(LinkedHashMap<String, String> arguments, HashMap<String, Object> wapper) {
		for (String key : arguments.keySet()) {
			String[] keyCells = key.split("#");
			String[] valueCells=arguments.get(key).split("#");
			String element=keyCells[0];
			if(valueCells.length>0){
				for(int i=0;i<valueCells.length;i++){
					if(!element.matches(valueCells[i])){
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", keyCells[i+1]);
						return;
					}
				}
			}
		}
	}

	/**
	 * 保存线路附件
	 * @param request
	 * @param wapper 用于装载操作结果
	 * @param routeId 线路id
	 * @param attachmentArray 附件集合
	 * @param groupNumber 附件组号
	 */
	private void saveRouteAttachmentInfo(HttpServletRequest request, HashMap<String, Object> wapper, String routeId,
			JSONArray attachmentArray,int groupNumber) {
		if (attachmentArray != null) {
			for (int i = 0; i < attachmentArray.size(); i++) {
				JSONObject object = attachmentArray.getJSONObject(i);
				String attachmentId=null;
				Attachment attachmentObject = new Attachment();
				ZtcRouteAttachment routeAttachment = new ZtcRouteAttachment();
				routeAttachment.setSequence(i);
				routeAttachment.setFkZtcRouteId(routeId);
				routeAttachment.setGroupNumber(groupNumber);
				if (object.get("img") != null&&!"".equals(object.get("img"))) {
					String image = object.getString("img");
					String[] imageElements=image.split(";");
					Date now=new Date();
					String time=String.valueOf(now.getTime());
					attachmentObject.setUploadTime(now);
					attachmentObject.setUploaderName("班次添加图片与说明");
					if (imageElements[0].contains("jpg")) {
						attachmentObject.setFileType("image/jpeg");
						attachmentObject.setFileName("线路图片"+time+".jpg");
						attachmentObject.setWorkItem("线路图片"+time+".jpg");
					}
					if (imageElements[0].contains("gif")) {
						attachmentObject.setFileType("image/gif");
						attachmentObject.setFileName("线路图片"+time+".gif");
						attachmentObject.setWorkItem("线路图片"+time+".jpg");
					}
					if (imageElements[0].contains("png")) {
						attachmentObject.setFileType("image/png");
						attachmentObject.setFileName("线路图片"+time+".png");
						attachmentObject.setWorkItem("线路图片"+time+".jpg");
					}
					String bodyInfo = imageElements[1];
					if (!"".equals(bodyInfo)) {
						String[] bodyInfos = bodyInfo.split(",");
						try {
							byte[] b = new BASE64Decoder().decodeBuffer(bodyInfos[1]);
							for (int j = 0; j < b.length; ++j) {
								if (b[j] < 0) {
									// 调整异常数据
									b[j] += 256;
								}
							}
							attachmentObject.setFileBody(b);
						} catch (IOException e) {
							e.printStackTrace();
						}
						attachmentId = attachmentManager.saveAttachment(attachmentObject, request, true);
						if (attachmentId == null) {
							wapper.put("success", Boolean.valueOf(false));
							wapper.put("msg", "网路错误");
							log.info("网络错误");
							return;
						}
						routeAttachment.setViewContent(object.getString("text"));
						routeAttachment.setFkAttachmentId(attachmentId);
						routeAttachment.setType(0);
					}
				}else{
					routeAttachment.setViewContent(object.getString("text"));
					routeAttachment.setFkAttachmentId("");
					routeAttachment.setType(1);
				}
				String ztcRouteId = ztcRouteAttachmentManager.save(routeAttachment);
				if (ztcRouteId == null) {
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "网路错误");
					log.info("网络错误");
					return;
				}
				if(attachmentId!=null){
					attachmentObject.setBusinessId(routeAttachment.getId());
					attachmentObject.setFilePath(attachmentId);
					attachmentManager.save(attachmentObject);
				}
			}
		}
	}

	/**
	 * 线路审核
	 * @param id 线路id
	 * @param examineRemark 审核意见
	 * @param endValidateTime 线路有效期截止时间
	 * @param isPass 是否通过：0.通过1.不通过
	 * @param session
	 * @return 返回操作结果信息
	 * @throws ParseException
	 */
	@RequestMapping("examine")
	@ResponseBody
	public HashMap<String, Object> examine(String id, String examineRemark, String endValidateTime, String isPass, HttpSession session) throws ParseException {
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if(user==null||"".equals(user)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		Date date = new Date();
		if("".equals(isPass)||isPass==null){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "线路状态不可为空");
			log.info("线路状态不可为空");
			return wapper;
		}
		argumentsAndRoles.put(isPass + "#线路状态格式如'1'", "^([0]|[1])$");
		examineArgument(argumentsAndRoles, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		Date startDate=date;
		int status=1;
		Date endDate=null;
		if("0".equals(isPass)){
			argumentsAndRoles.clear();
			if("".equals(endValidateTime)||endValidateTime==null){
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "线路有效期截止时间不可为空");
				log.info("线路有效期截止时间不可为空");
				return wapper;
			}
			argumentsAndRoles.put(endValidateTime + "#线路结束时间格式如'2017-12-23'",
					"^[2][0-9]{3}-(([0][1-9])|([1][0-2]))-(([1-2][0-9])|([0][1-9])|([3][0-1]))$");
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
			endDate=DATE_FORMET.parse(endValidateTime);
		}else{
			status=2;
			startDate=null;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作线路");
			log.info("非运营公司或车方不可操作线路");
			return wapper;
		}
		if(transport.getStatus()==4){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可审核线路");
			log.info("该用户公司已被冻结，不可审核线路");
			return wapper;
		}
		ZtcRoute route = new ZtcRoute();
		route.setId(id);
		ZtcRoute routeBean = ztcRouteManager.searchInfoEquals(route).get(0);
		routeBean.setExamineRemark(examineRemark);
		routeBean.setExamineTime(date);
		routeBean.setExamineUserName(user == null ? ""
				: (user.getName() == null || "".equals(user.getName())) ? user.getAccount() : user.getName());
		routeBean.setFkExamineUserId(user == null ? "" : user.getId());
	    routeBean.setStatus(status);
		routeBean.setBeginValidateTime(startDate);
		routeBean.setEndValidateTime(endDate);
		String routeId = ztcRouteManager.update(routeBean);
		if ("0".equals(routeId)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网路错误");
			log.info("网络错误");
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "审核成功");
		log.info("审核成功");
		return wapper;
	}

	/**
	 * 禁用某条线路
	 * @param id 线路id
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException
	 */
	@RequestMapping("stop")
	@ResponseBody
	public HashMap<String, Object> stop(String id, HttpSession session) throws ParseException {
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if(user==null||"".equals(user)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作线路");
			log.info("非运营公司或车方不可操作线路");
			return wapper;
		}
		if(transport.getStatus()==4){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可禁用线路");
			log.info("该用户公司已被冻结，不可禁用线路");
			return wapper;
		}
		ZtcRoute route = new ZtcRoute();
		route.setId(id);
		ZtcRoute routeBean = ztcRouteManager.searchInfoEquals(route).get(0);
		Date now = new Date();
		routeBean.setUpdateTime(now);
		routeBean.setStatus(3);
		routeBean.setUpdateUserName(user == null ? ""
				: (user.getName() == null || "".equals(user.getName())) ? user.getAccount() : user.getName());
		routeBean.setFkUpdateUserId(user == null ? "" : user.getId());
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setFkZtcRouteId(id);
		List<ZtcClasses> ztcClassesList = ztcClassesManager.searchInfoEquals(ztcClasses);
		for (int i = 0; i < ztcClassesList.size(); i++) {
			ZtcClasses ztcClassesBean = ztcClassesList.get(i);
			List<ZtcClassesForSale> ztcClassesForSales = ztcClassesForSaleDao.findBy("fkZtcClassesId",ztcClassesBean.getId(),"ticketStatus",0);
			for (int j = 0; j < ztcClassesForSales.size(); j++) {
				ZtcClassesForSale element = ztcClassesForSales.get(j);
				element.setFkModifyUserId(user == null ? "" : user.getId());
				element.setModifyTime(now);
				String result = ztcClassesForSaleManager.stopSell(element,user,now);
				if ("0".equals(result)) {
					wapper.put("success",Boolean.valueOf(false));
					wapper.put("msg", "操作失败");
					return wapper;
				}
			}
			ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
			ztcClassesBean.setModifyTime(now);
			ztcClassesBean.setTicketStatus(1);
			String updateResult = ztcClassesManager.update(ztcClassesBean);
			if ("0".equals(updateResult)) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "网路错误");
				log.info("网络错误");
				return wapper;
			}
		}
		String routeId = ztcRouteManager.update(routeBean);
		if ("0".equals(routeId)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网路错误");
			log.info("网络错误");
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "禁用成功");
		log.info("禁用成功");
		return wapper;
	}

	@RequestMapping("get")
	@ResponseBody
	public HashMap<String, Object> get(String id, HttpSession session) {
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if(user==null||"".equals(user)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcRoute ztcRouteExemple = new ZtcRoute();
		ztcRouteExemple.setId(id);
		ZtcRoute ztcRoute = ztcRouteManager.searchInfoEquals(ztcRouteExemple).get(0);
		List<ZtcRouteSite> routeSites =ztcRouteManager.getSites(ztcRoute);;
		List<ZtcRoutePrice> routePrices = ztcRouteManager.getPrices(ztcRoute);
		List<ZtcRouteAttachment> routeAttachments = ztcRouteManager.getAttachments(ztcRoute);
		String data = generateData(routeSites, routePrices);
		String attachment = generateAttachment(routeAttachments);
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("routeId", ztcRoute.getId());
		wapper.put("name", ztcRoute.getName());
		wapper.put("remark", ztcRoute.getRemark());
		wapper.put("data", JSON.parseArray(data));
		wapper.put("attachment", JSON.parseArray(attachment));
		return wapper;
	}

	/**
	 * 以线路站点集合，价格集合生成页面可以展示的梯形表数据
	 * @param routeSites 线路站点集合
	 * @param routePrices 线路价格集合
	 * @return 页面可以展示的梯形表数据
	 */
	private String generateData(List<ZtcRouteSite> routeSites, List<ZtcRoutePrice> routePrices) {
		String data = "[";
		List<ZtcRouteSite> startZtcRouteSites = new ArrayList<ZtcRouteSite>();
		for (int i = 0; i < routeSites.size(); i++) {
			ZtcRouteSite endZctRoutesite = routeSites.get(i);
			String cell = "[";
			for (int j = 0; j < startZtcRouteSites.size(); j++) {
				ZtcRouteSite startZtcRoute = startZtcRouteSites.get(j);
				if (routePrices.size() == 0) {
					cell += "{\"pirce\":\"\",\"distance\":\"\"}";
					if (j != startZtcRouteSites.size() - 1) {
						cell += ",";
					}
				} else {
					boolean findResult = false;
					int index = 0;
					for (int k = 0; k < routePrices.size(); k++) {
						ZtcRoutePrice routePrice = routePrices.get(k);
						if (startZtcRoute.getId().equals(routePrice.getFkRouteStartSiteId())
								&& endZctRoutesite.getId().equals(routePrice.getFkRouteEndSiteId())) {
							index = k;
							cell += "{\"startName\":\""+ startZtcRoute.getAreaCity() + "\","
									+ "\"pirce\":\"" + routePrice.getPrice() + "\","
									+ "\"distance\":\""+ routePrice.getDistance() + "\","
									+ "\"endName\":\""+ endZctRoutesite.getAreaCity()+ "\"}";
							if (j != startZtcRouteSites.size() - 1) {
								cell += ",";
							}
							findResult = true;
							break;
						}
					}
					if (findResult) {
						routePrices.remove(index);
					} else {
						cell += "{\"pirce\":\"\",\"distance\":\"\"}";
						if (j != startZtcRouteSites.size() - 1) {
							cell += ",";
						}
					}
				}
			}
			cell += "]";
			if (i == 0) {
				data += "{\"name\":\"" + (endZctRoutesite.getAreaCity() == null ? "" : endZctRoutesite.getAreaCity())
						+ "\",\"remark\":\"起点\"," + "\"lat\":\"" + endZctRoutesite.getLat() + "\"," + "\"detailed\":\""
						+ (endZctRoutesite.getName() == null ? "" : endZctRoutesite.getName()) + "\"}";
			} else if (i == routeSites.size() - 1) {
				data += "{\"name\":\"" + (endZctRoutesite.getAreaCity() == null ? "" : endZctRoutesite.getAreaCity())
						+ "\",\"remark\":\"终点\"," + "\"lat\":\"" + endZctRoutesite.getLat() + "\"," + "\"detailed\":\""
						+ (endZctRoutesite.getName() == null ? "" : endZctRoutesite.getName()) + "\",\"cell\":" + cell
						+ "}";
			} else {
				data += "{\"name\":\"" + (endZctRoutesite.getAreaCity() == null ? "" : endZctRoutesite.getAreaCity())
						+ "\",\"lat\":\"" + endZctRoutesite.getLat() + "\"," + "\"detailed\":\""
						+ (endZctRoutesite.getName() == null ? "" : endZctRoutesite.getName()) + "\",\"cell\":" + cell
						+ "}";
			}
			startZtcRouteSites.add(endZctRoutesite);
		}
		data += "]";
		return data;
	}

	/**
	 * 以线路附件集合生成页面可以展示的附件信息
	 * @param routeAttachments 线路附件集合
	 * @return 页面可以展示的附件信息
	 */
	private String generateAttachment(List<ZtcRouteAttachment> routeAttachments) {
		int groupIndex=0;
		int groupNumber=0;
		if(routeAttachments.size()>0){
			groupNumber=routeAttachments.get(0).getGroupNumber();
		}
		int count=0;
		String attachmentValue = "[";
		while(true){
			String attachmentElement="{\"group\":[";
			for (int i = groupIndex; i < routeAttachments.size(); i++) {
				ZtcRouteAttachment routeAttachment = routeAttachments.get(i);
	            if(routeAttachment.getGroupNumber()!=groupNumber){
	            	groupIndex=i;
	            	groupNumber=routeAttachment.getGroupNumber();
	            	break;
	            }
				if (routeAttachment.getFkAttachmentId() == null || "".equals(routeAttachment.getFkAttachmentId())) {
					attachmentElement += "{\"img\":\"\",\"text\":\""+ routeAttachment.getViewContent() +"\"}";
				} else {
					Attachment attachment = routeAttachment.getAttachment();
					attachmentElement += "{\"img\":\"data:"+ attachment.getFileType() + ";base64," + getFileBody(attachment.getFileBody())+ "\",\"text\":\""+routeAttachment.getViewContent()+"\"}";
				}
				count++;
			}
			if(count==routeAttachments.size()){
				attachmentElement+="]}";
				attachmentValue+=attachmentElement;
				break;
			}else{
				attachmentElement+="]},";
				attachmentValue+=attachmentElement;
			}
		}
		attachmentValue += "]";
		return attachmentValue;
	}

	/**
	 * 解密图片base64数据
	 * @param fileBody 图片base64数据
	 * @return 解密后的base64数据
	 */
	private String getFileBody(byte[] fileBody) {
		for (int j = 0; j < fileBody.length; ++j) {
			if (fileBody[j] > 0) {
				// 调整异常数据
				fileBody[j] -= 256;
			}
		}
		String bodyInfo = new BASE64Encoder().encode(fileBody);
		return bodyInfo;
	}

	/**
	 * 根据页数，名称获取用于班次发布的线路信息
	 * @param pageNumber 第几页
	 * @param name 名称
	 * @param session
	 * @return 用于班次发布的线路信息
	 */
	@RequestMapping("getListForClassesPublish")
	@ResponseBody
	public HashMap<String, Object> getListForClassesPublish(String pageNumber, String name, HttpSession session) {
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if(user==null||"".equals(user)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if (pageNumber != null) {
			argumentsAndRoles.put(pageNumber + "#页数必须为数字", "^(([0-9])|([1-9][0-9]{0,}))$");
			examineArgument(argumentsAndRoles, wapper);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		ZtcRoute route = new ZtcRoute();
		route.setName(name);
		List<ZtcRoute> list = new ArrayList<>();
		list = ztcRouteManager.searchInfoLikesForClassesPublish(route, transport, pageNumber);
		String stringList = generateList(list);
		JSONArray jsonList = JSON.parseArray(stringList);
		wapper.put("list", jsonList);
		wapper.put("listSize", ztcRouteManager.countForPublish(route, transport));
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("name", name);
		wapper.put("pageNumber", pageNumber);
		return wapper;
	}

	/**
	 * 根据页数，名称，功能模块获取线路信息
	 * @param pageNumber 第几页
	 * @param name 名称
	 * @param moduleNumber 功能模块号：0.线路（待）审核1.线路信息
	 * @param session
	 * @return 线路信息
	 */
	@RequestMapping("getList")
	@ResponseBody
	public HashMap<String, Object> getList(String pageNumber, String name, String moduleNumber, HttpSession session) {
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if(user==null||"".equals(user)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if (pageNumber != null) {
			argumentsAndRoles.put(pageNumber + "#页数必须为数字", "^(([0-9])|([1-9][0-9]{0,}))$");
			examineArgument(argumentsAndRoles, wapper);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		ZtcRoute route = new ZtcRoute();
		route.setName(name);
		List<ZtcRoute> list = new ArrayList<>();
		list = ztcRouteManager.searchInfoLikes(route,transport, pageNumber, moduleNumber);
		String stringList = generateList(list);
		JSONArray jsonList = JSON.parseArray(stringList);
		wapper.put("list", jsonList);
		wapper.put("listSize", ztcRouteManager.count(route, transport, moduleNumber));
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("name", name);
		wapper.put("pageNumber", pageNumber);
		return wapper;
	}

	/**
	 * 以线路集合生成用于页面展示的线路信息
	 * @param list 线路集合
	 * @return 页面展示的线路信息
	 */
	private String generateList(List<ZtcRoute> list) {
		String stringList = "[";
		for (int i = 0; i < list.size(); i++) {
			ZtcRoute ztcRoute = list.get(i);
			String element = "{\"name\":\"" + ztcRoute.getName() + "\",\"remark\":\"" + ztcRoute.getRemark()
					+ "\",\"addTime\":\"" + ztcRoute.getAddTime() + "\",\"status\":\"" + ztcRoute.getStatus()
					+ "\",\"applyUserName\":\"" + ztcRoute.getApplyUserName();
			List<ZtcRouteSite> sites = ztcRouteManager.getSites(ztcRoute);
			ZtcRouteSite startSite = sites.get(0);
			ZtcRouteSite endSite = sites.get(sites.size() - 1);
			element += "\",\"startSiteName\":\"" + startSite.getAreaCity() + "\",\"startSiteAreaCity\":\""
					+ startSite.getName() + "\",\"endSiteName\":\"" + endSite.getAreaCity()
					+ "\",\"endSiteAreaCity\":\"" + endSite.getName();
			element += "\",\"routeId\":\"" + ztcRoute.getId();
			element += "\",\"cell\":[";
			for (int j = 0; j < sites.size(); j++) {
				ZtcRouteSite routeSite = sites.get(j);
				if (j == 0) {
					element += "{\"name\":\"" + routeSite.getAreaCity() + "\",\"remark\":\"起点\",\"sequence\":\""
							+ routeSite.getSequence() + "\",\"areaCity\":\"" + routeSite.getName() + "\",\"lat\":\""
							+ routeSite.getLat() + "\"," + "\"areaCode\":\"" + routeSite.getAreaCode() + "\",\"lat\":\""
							+ routeSite.getLat() + "\"},";
				} else if (j == sites.size() - 1) {
					element += "{\"name\":\"" + routeSite.getAreaCity() + "\",\"remark\":\"终点\",\"sequence\":\""
							+ routeSite.getSequence() + "\",\"areaCity\":\"" + routeSite.getName() + "\",\"lat\":\""
							+ routeSite.getLat() + "\"," + "\"areaCode\":\"" + routeSite.getAreaCode() + "\",\"lat\":\""
							+ routeSite.getLat() + "\"}";
				} else {
					element += "{\"name\":\"" + routeSite.getAreaCity() + "\",\"sequence\":\"" + routeSite.getSequence()
							+ "\",\"lat\":\"" + routeSite.getLat() + "\"," + "\"areaCity\":\"" + routeSite.getName()
							+ "\",\"areaCode\":\"" + routeSite.getAreaCode() + "\",\"lat\":\"" + routeSite.getLat()
							+ "\"},";
				}
			}
			element += "]}";
			stringList += element;
			if (i != list.size() - 1) {
				stringList += ",";
			}
		}
		stringList += "]";
		return stringList;
	}

	/**
	 * 根据公司ID获取线路列表信息.
	 * @return 线路（经纬度）
	 */
	@RequestMapping("getRouteListMapByTid")
	@ResponseBody
	public HashMap<String, Object> getRouteListMapByTid(HttpSession session){
		User user=(User)session.getAttribute("userInfo");
		return JsonWrapper.successWrapper(ztcRouteManager.getRouteListMapByTid(user.getTransportId(),ztcTransportManager.get(user.getTransportId()).getType()));
	}
}